/*
 * Contains everything gameplay related. The Arena is the game.
 * 
 */
package com.cmp.arena;

import com.cmp.arena.controls.BallControl;
import com.cmp.arena.controls.GoalControl;
import com.cmp.player.controls.CollisionControl;
import com.cmp.player.controls.ScoreControl;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.shapes.BoxCollisionShape;
import com.jme3.bullet.control.GhostControl;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;

/**
 * Create a goal and stuff.
 * @author krummer
 */
public class GoalFactory {
    /**
     * Transform a node into a goal trigger node.
     * @param goal the goal node
     * @param halfExtends how big the goal is (it's a box)
     * @param team which team the goal belongs to
     */
    public static void makeGoal(Node goal, final boolean team) {
        goal.setUserData("Team", team);
        goal.addControl(new GoalControl());
        
        BoxCollisionShape shape = new BoxCollisionShape( goal.getLocalScale().clone());
        GhostControl body = new GhostControl(shape);
        goal.addControl(body);
        
        //add collision
        goal.addControl(new CollisionControl() {

            @Override
            public void onCollision(PhysicsCollisionEvent event, 
                                     Spatial other, boolean isA) {
                if(other instanceof Node) {
                    //check if player.
                    if(other.getUserData("isPlayer") != null) {
                        //check for team
                        boolean playerTeam = other.getUserData("Team");
                        
                        //check for ball
                        if(team != playerTeam) {
                           Spatial ball = ((Node)other).getChild("Ball");
                           if( ball != null ) {
                               //get ball back to arena
                               ball.getControl(BallControl.class).respawn();
                               
                               //add score if there is a scorekeeper
                               ScoreControl score = other.getControl(ScoreControl.class);
                               if(score != null) {
                                   score.score();
                               }
                           }
                       }
                    }
                }
            }

            public Control cloneForSpatial(Spatial spatial) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
        
    }
}
